package com.jianyun.jyzs;

import android.Manifest;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.ArraySet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jianyun.jyzs.activity.HtmlActivity;
import com.jianyun.jyzs.activity.SplashActivity;
import com.jianyun.jyzs.base.MVPBaseActivity;
import com.jianyun.jyzs.bean.BadgeBean;
import com.jianyun.jyzs.bean.UrlConfig;
import com.jianyun.jyzs.dao.BadgeDao;
import com.jianyun.jyzs.db.EventCount;
import com.jianyun.jyzs.fragment.ContactFragment;
import com.jianyun.jyzs.fragment.MeFragment;
import com.jianyun.jyzs.fragment.OaCustomFragment;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.MainActHandler;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.presenter.MainPresenter;
import com.jianyun.jyzs.receive.LocalBroadcastManager;
import com.jianyun.jyzs.update.DownloadUtils;
import com.jianyun.jyzs.update.UpdateDialog;
import com.jianyun.jyzs.utils.AppShortCutUtil;
import com.jianyun.jyzs.utils.ExampleUtil;
import com.jianyun.jyzs.utils.LocationManager;
import com.jianyun.jyzs.utils.Logger;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.PhotoUtils;
import com.jianyun.jyzs.utils.SPUtils;
import com.jianyun.jyzs.utils.UpDateAPKUtil;
import com.jianyun.jyzs.utils.Utils;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.IMainView;
import com.jianyun.jyzs.widget.OptionMenu;
import com.jianyun.jyzs.widget.PromptDialog;
import com.jianyun.jyzs.widget.TabIndicatorItemView;
import com.jianyun.jyzs.widget.badge.BadgeHandler;
import com.jrmf360.rylib.common.util.ToastUtil;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.rongcloud.rce.lib.ConfigTask;
import io.rong.eventbus.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


//AppCompatActivity
public class MainActivity extends MVPBaseActivity<IMainView, MainPresenter> implements IMainView {

    @BindView(R.id.view_pager_main)
    ViewPager viewPager;
    @BindView(R.id.ll_tab_indicator)
    LinearLayout indicator;
    @BindView(R.id.tiiv_contact)
    TabIndicatorItemView indicatorContact;
    @BindView(R.id.tiiv_oa)
    TabIndicatorItemView indicatorOA;
    @BindView(R.id.tiiv_me)
    TabIndicatorItemView indicatorMe;

    public boolean isCommonContact = false;

    public boolean isSynchContact = false;//是否正在同步通讯录,控制在同步期间,通信录页面不展示,否则会有异常
    private static final String FRAGMENTS_TAG = "android:support:fragments";
    public MainActHandler mainActHandler = new MainActHandler(this);
    private static final int TAB_CONTACTS_INDEX = 1;
    private static final int TAB_OA_INDEX = 0;
    private static final int TAB_ME_INDEX = 2;
    private static final int READ_EXTERANL = 100;

    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static boolean isForeground = false;

    private int tabIndex;
    private String userId;
    private ArrayList<Fragment> fragmentList;
    private ContactFragment contactFragment;
    //private OAFragment oaFragment;
    private OaCustomFragment oaCustomFragment;
    private MeFragment meFragment;
    private ImageView leftIcon;
    private ImageButton searchButton;
    private ImageButton moreOptionButton;
    private OptionMenu optionMenu;
    private TextView tabName;
    private String androidDownLoad = "";//"http://cloud.yuntech.cc/YunCenter/AffixFile/yuntech_basic_jianyunzhushou/jyzs_1.2.0.apk?a=1&filename=jyzs_1.2.0.apk";
    private boolean isHintHelplerTv; //是否显示 帮助
    public TextView tvUserHelper;
    private String enterpriseCode;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        UtilsStyle.setStatusBarMode(this, true);
        if (savedInstanceState != null) {
            //activity 回收恢复时，重新生成 fragment。
            savedInstanceState.putParcelable(FRAGMENTS_TAG, null);
        }
        super.onCreate(savedInstanceState);


        setContentView(R.layout.rce_activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        initUpdateApp();
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        initView();
        registerMessageReceiver();  // used for receive msg
        getFlowCount();
    }

    /**
     * 更新APP
     */
    private void initUpdateApp() {
        UrlConfig urlConfig = LoginCache.getInstance().getLoginCache();
        androidDownLoad = urlConfig.getAndroidDownLoad();
        String androidVersion = "";
        try {
            androidVersion = androidDownLoad.substring(androidDownLoad.lastIndexOf(".apk") - 5, androidDownLoad.lastIndexOf(".apk"));
        } catch (Exception e) {
            androidVersion = Utils.getVersionName(this);
            e.printStackTrace();
        }

        int newverCode = 0;
        String newVersion = urlConfig.getAndroidVersionCode();
        if (newVersion != null) newverCode = Integer.parseInt(newVersion);
        int oldverCode = Utils.getVerCode(this);
        String isForceUpdate = urlConfig.getIsForceUpdate();

        UpdateDialog updateDialog = UpdateDialog.getInstance(this, "最新版本：V " + androidVersion, "");
        updateDialog.setPromptButtonClickedListener(new UpdateDialog.OnDialogButtonClickedListener() {
            @Override
            public void onPositiveButtonClicked() {
                if (androidDownLoad != null) {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        UpDateAPKUtil.getInstance().cretaDownTask(MainActivity.this, androidDownLoad, "建云助手.apk");
                        // new DownloadUtils(MainActivity.this).downloadAPK(androidDownLoad, "建云助手.apk");

                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, READ_EXTERANL);
                    }

                }
            }

            @Override
            public void onNegativeButtonClicked() {

            }
        });
        try {
            if (newverCode > oldverCode) {
                if ("1".equals(isForceUpdate)) {
                    updateDialog.disableCancel();
                }
                updateDialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        LocationManager locationManager = new LocationManager(this);
        locationManager.locationStart();
        UrlConfig loginCache = LoginCache.getInstance().getLoginCache();
        androidDownLoad = loginCache.getAndroidDownLoad();


        indicatorContact.setRemindType(TabIndicatorItemView.RemindType.REMIND_TEXT);
        indicatorContact.setDraggable(false);
        indicatorMe.setRemindType(TabIndicatorItemView.RemindType.REMIND_NORMAL);
        fragmentList = new ArrayList<>();

        contactFragment = new ContactFragment();
        //oaFragment = new OAFragment();
        oaCustomFragment = new OaCustomFragment();
        meFragment = new MeFragment();
        fragmentList.add(oaCustomFragment);
        fragmentList.add(contactFragment);
        fragmentList.add(meFragment);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }
        });
        viewPager.setOverScrollMode(View.OVER_SCROLL_NEVER);
        viewPager.setOffscreenPageLimit(fragmentList.size());

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        if (tabName != null) tabName.setText("应用");
                        break;
                    case 1:
                        if (tabName != null) tabName.setText("通讯录");
                        break;
                    case 2:
                        if (tabName != null) tabName.setText("我");
                        break;
                }
                for (int i = 0; i < indicator.getChildCount(); i++) {
                    View child = indicator.getChildAt(i);
                    child.setSelected(i == position);
                }
                refreshActionBar(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        viewPager.setCurrentItem(0);
        View child = indicator.getChildAt(0);
        child.setSelected(true);
        getRessId();
        oaCustomFragment.setOngetListener(new OaCustomFragment.OngetListener() {
            @Override
            public void setView(Boolean visibility) {
                isHintHelplerTv = visibility;
                if (visibility) {
                    tvUserHelper.setVisibility(View.VISIBLE);
                } else {
                    tvUserHelper.setVisibility(View.INVISIBLE);
                }

            }
        });
    }

    @NonNull
    @Override
    public MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @OnClick({R.id.tiiv_contact, R.id.tiiv_oa, R.id.tiiv_me})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tiiv_contact:
                viewPager.setCurrentItem(TAB_CONTACTS_INDEX, false);
                refreshActionBar(TAB_CONTACTS_INDEX);
                break;
            case R.id.tiiv_oa:
                viewPager.setCurrentItem(TAB_OA_INDEX, false);
                refreshActionBar(TAB_OA_INDEX);
                break;
            case R.id.tiiv_me:
                viewPager.setCurrentItem(TAB_ME_INDEX, false);
                indicatorMe.setRemindVisible(false);
                tabIndex = TAB_ME_INDEX;
                refreshActionBar(TAB_ME_INDEX);
                break;
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    public void getRessId() {
        String rid = JPushInterface.getRegistrationID(getApplicationContext());
        String userId = LoginCache.getInstance().getUserInfo().getUserId();
        if (!rid.isEmpty()) {
            Logger.i(TAG, "注册RegId:" + rid);
            upRegistrationId(userId);
        } else {
            Toast.makeText(this, "Get registration fail, JPush init failed!", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 上传RegistrationId
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void upRegistrationId(String userId) {
        Set<String> tags = new ArraySet<>();
        tags.add(enterpriseCode);
        JPushInterface.addTags(this, 202, tags);//添加标签
        //JPushInterface.setAlias(this, 203, userId);//设置别名
        String rid = JPushInterface.getRegistrationID(getApplicationContext());
        if (!rid.isEmpty()) {
            Api api = RetrofitHelper.builderCeshiHttp().create(Api.class);
            Log.i("test", "userid:" + userId + "\nrid:" + rid);
            api.upRegId("SaveRegistration_id", userId, rid,
                    "jyzs", "Android", "1.0.2")
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Subscriber<Object>() {
                        @Override
                        public void onError(Throwable e) {
                            Log.i("test", "设备ID上传失败");
                            e.printStackTrace();
                        }

                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onNext(Object o) {
                            String s = new Gson().toJson(o);
                            Log.i("test", "上传RegistrationId：" + s.toString());
                        }
                    });
        }

    }

    @Override
    public void onCreateActionBar(ActionBar actionBar) {
        final View actionBarView = actionBar.setActionBar(R.layout.rce_actionbar_main);
        leftIcon = (ImageView) actionBarView.findViewById(R.id.imgbtn_actionbar_icon);
        searchButton = (ImageButton) actionBarView.findViewById(R.id.imgBtn_actionbar_search);
        moreOptionButton = (ImageButton) actionBarView.findViewById(R.id.imgBtn_actionbar_option_add);
        tvUserHelper = actionBarView.findViewById(R.id.tv_user_helper);
        tabName = (TextView) findViewById(R.id.tv_actionbar_name);
        tabName.setText("应用");
        searchButton.setVisibility(View.GONE);
        moreOptionButton.setVisibility(View.GONE);
        tvUserHelper.setVisibility(View.VISIBLE);
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });


        moreOptionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (tabIndex) {

                    case TAB_CONTACTS_INDEX:

                        break;

                    default:
                        break;
                }
            }
        });
        tvUserHelper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (oaCustomFragment.help_url != null && !TextUtils.isEmpty(oaCustomFragment.help_url)) {
                    Intent intent = new Intent(MainActivity.this, HtmlActivity.class);
                    intent.putExtra("urlUserHelper", oaCustomFragment.help_url);
                    startActivity(intent);
                }


            }
        });


    }

    private void refreshActionBar(int tabIndex) {
        searchButton.setVisibility(View.GONE);
        moreOptionButton.setVisibility(View.GONE);
        switch (tabIndex) {

            case TAB_CONTACTS_INDEX:
                this.tabIndex = TAB_CONTACTS_INDEX;
                setActionBarButtonVisible(true);
                moreOptionButton.setImageResource(R.drawable.rce_ic_nav_option_addfriend);
                tvUserHelper.setVisibility(View.INVISIBLE);
                break;
            case TAB_OA_INDEX:
                this.tabIndex = TAB_OA_INDEX;
                setActionBarButtonVisible(false);
                if (isHintHelplerTv) {
                    tvUserHelper.setVisibility(View.VISIBLE);
                } else {
                    tvUserHelper.setVisibility(View.INVISIBLE);
                }
                break;
            case TAB_ME_INDEX:
                this.tabIndex = TAB_ME_INDEX;
                setActionBarButtonVisible(false);
                tvUserHelper.setVisibility(View.INVISIBLE);
                break;
        }
    }


    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();

        searchButton.setVisibility(View.GONE);
        moreOptionButton.setVisibility(View.GONE);
        BadgeHandler.getInstance().updateBadgeCount(0);
        // FriendTask.getInstance().addFriendRequestUnreadCountChangedObserver(this);
        //设置 应用红色角标
        int Spcount = (int) SPUtils.get(this, userId, 0);
        setOaCount(Spcount);

    }

    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
//            moveTaskToBack(false);
            if (System.currentTimeMillis() - mExitTime > 2000) {
                mExitTime = System.currentTimeMillis();
                ToastUtil.showNoWaitToast(MainActivity.this, "再次点击退出应用");
                return false;
            } else {
                finish();
                System.exit(0);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == READ_EXTERANL) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                new DownloadUtils(this).downloadAPK(androidDownLoad, "建云助手.apk");

            } else {
                PromptDialog dialog = PromptDialog.newInstance(MainActivity.this, "请开启存储权限", "");
                dialog.setCancelable(false);
//                dialog.disableCancel();
                dialog.setPromptButtonClickedListener(new PromptDialog.OnPromptButtonClickedListener() {
                    @Override
                    public void onPositiveButtonClicked() {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERANL);
                    }

                    @Override
                    public void onNegativeButtonClicked() {
                        finish();
                    }
                });
                dialog.show();

            }
        }

        if (requestCode == DownloadUtils.MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                new DownloadUtils(this).cretaDowloadTask(androidDownLoad, "建云助手.apk");
            } else {
                PromptDialog dialog = PromptDialog.newInstance(MainActivity.this, "请开启存储权限", "");
                dialog.setCancelable(false);
//                dialog.disableCancel();
                dialog.setPromptButtonClickedListener(new PromptDialog.OnPromptButtonClickedListener() {
                    @Override
                    public void onPositiveButtonClicked() {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERANL);
                    }

                    @Override
                    public void onNegativeButtonClicked() {
                        finish();
                    }
                });
                dialog.show();

            }
        }
    }

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

    private void setActionBarButtonVisible(boolean visible) {
//        searchButton.setVisibility(visible ? View.VISIBLE : View.GONE);
//        moreOptionButton.setVisibility(visible ? View.VISIBLE : View.GONE);
        if (ConfigTask.getInstance().isEnableConferenceCall()) {
//            callButton.setVisibility(visible ? View.VISIBLE : View.GONE);
        }
    }

    /**
     * 设置应用红色角标
     *
     * @param count
     */
    private void setOaCount(int count) {
        Log.i("test", "角标数目：" + count);
        if (count != 0) {
            indicatorOA.setRemindVisible(true);
            //AppShortCutUtil.addNumShortCut(MainActivity.this, SplashActivity.class, true, count + "", false);
            if (count > 0 && count < 100) {
                indicatorOA.setRemindText(String.format("%s", count));
            } else {
                indicatorOA.setRemindText(getString(R.string.rce_no_read_message));
            }

        } else {
            indicatorOA.setRemindVisible(false);
        }


    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    setCostomMsg(showMsg.toString());
                }
            } catch (Exception e) {
            }
        }
    }

    public Handler Myhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            EventCount eventCount = (EventCount) msg.obj;

            int count = eventCount.getCount();
            setOaCount(count);
        }
    };

    public void onEvent(EventCount eventCount) {
        int count = eventCount.getCount();
        Log.i("test", "收到通知个数：" + eventCount.getCount());
        Myhandler.obtainMessage(1, eventCount).sendToTarget();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PhotoUtils.INTENT_CROP:
                if (resultCode == RESULT_OK) {
                    meFragment.loadingDialog.show();
                }
                meFragment.uploadPortrait.getPhotoUtils().onActivityResult(this, requestCode, resultCode, data);
                break;
            case PhotoUtils.INTENT_TAKE:
            case PhotoUtils.INTENT_SELECT:
                meFragment.uploadPortrait.getPhotoUtils().onActivityResult(this, requestCode, resultCode, data);
                break;
        }
    }

    private void setCostomMsg(String msg) {
        Logger.i("test", "推送：" + msg);

    }

    //获取待办总数
    private void getFlowCount() {
        //final String userId = CacheTask.getInstance().getUserId();
        final BadgeDao badgeDao = new BadgeDao(this);
        Api api = RetrofitHelper.builderErpRoot().create(Api.class);
        api.getFlowCount("GetMyDealingTaskCount", userId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onNext(Object o) {
                        String s = new Gson().toJson(o);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getBoolean("result")) {
                                int Spcount = (int) SPUtils.get(MainActivity.this, userId, 0);
                                int total = jsonObject.getInt("total");
                                Log.i("test", "Main待办数据：" + total);
                                if (Spcount != total) {
                                    EventBus.getDefault().post(new EventCount("workflow_count", total));
                                    //保存待办个数
                                    SPUtils.put(MainActivity.this, userId, total);
                                    boolean exist = badgeDao.isExist(userId);
                                    if (!exist) {
                                        BadgeBean badgeBean = new BadgeBean();
                                        badgeBean.setOaCount(total);
                                        badgeBean.setUserId(userId);
                                        badgeDao.insert(badgeBean);
                                    } else {
                                        BadgeBean badgeBean = badgeDao.queryByUserid(userId);
                                        badgeBean.setOaCount(total);
                                        badgeDao.updateBean(badgeBean);
                                    }
                                    setOaCount(total);
                                    BadgeBean badgeBean = badgeDao.queryByUserid(userId);
                                    if (badgeBean != null) {
                                        int totalCount = badgeBean.getMsgCount() + badgeBean.getOaCount();
                                        BadgeHandler.getInstance().updateBadgeCount(totalCount);

                                    } else {
                                        Log.i("test", "数据库中的：无数据");
                                    }
                                    //BadgeBean badgeBean = new BadgeBean();
                                }

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

    }


}
